<?php

namespace App\Services;

use App\Models\ExamPaper;
use App\Models\ExamPaperQuestion;
use App\Models\ExamQuestionOption;
use App\Models\Question;
use App\Models\UserExamRecord;
use App\Models\UserQuestionRecord;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class ExamPaperService extends BaseService
{
    /**
     * 获取列表
     * @return
     */
    public function list($page,$limit,$sort,$order,$name,$exam_category_id,$certificate_id,$is_published) {
        $query = ExamPaper::leftJoin('certificates', 'certificates.id', '=', 'exam_papers.certificate_id')
            ->leftJoin('exam_categories', 'exam_categories.id', '=', 'exam_papers.exam_category_id')
            ->select('exam_papers.*',
                'certificates.name as certificatesName','exam_categories.name as categoriesName'
            );
        if(!empty($name)){
            $query->where('exam_papers.name','like',"%$name%");
        }
        if(!empty($exam_category_id)){
            $query->where('exam_category_id',$exam_category_id);
        }
        if(!empty($certificate_id)){
            $query->where('certificate_id',$certificate_id);
        }
        if(!empty($is_published)){
            $query->where('is_published',$is_published);
        }

        return $query->orderBy($sort,$order)->paginate($limit, ['*'], 'page', $page);
    }

    /**
     * 获取未引用试题列表
     * @return
     */
    public function unreferencedQuestion($question_category_id,$question_type,$examPaperQuestionIds) {
        // 检索单选题
        $query = Question::whereNotIn('id', $examPaperQuestionIds);
        if(!empty($name)){
            $query->where('name','like',"%$name%");
        }
        if(!empty($question_category_id)){
            $query->where('question_category_id', $question_category_id);
        }
        if(!empty($question_type)){
            $query->where('question_type', $question_type);
        }
        $query->select('id','name','stem','question_type');
        return $query->get();
    }
    /**
     * 获取试卷下试题列表
     * @return
     */
    public function listPaperQuestion($exam_paper_id) {
        // 检索单选题
        $exam = ExamPaperQuestion::where('exam_paper_id', $exam_paper_id)
            ->select('id','name','question_stem','question_type','order','score','is_required','is_displayed')
            ->orderBy('order','asc')
            ->get()->toArray();
        // 提取试题的ID
        $examQuestionIds = array_column($exam, 'id');
        // 查询选项
        $options = ExamQuestionOption::whereIn('exam_paper_question_id', $examQuestionIds)
            ->select('id','exam_paper_question_id','option_content','is_correct','order')
            ->orderBy('order','asc')->get();

        $examWithOptions = [];
        // 遍历试题
        foreach ($exam as $k=>$v) {
            $exam[$k]['options'] = [];
            $examWithOptions[$v['id']] = $exam[$k];
        }

        // 遍历选项，将选项与试题关联
        $options = $options->toArray();
        foreach ($options as $option) {
            if (isset($examWithOptions[$option['exam_paper_question_id']])) {
                $examWithOptions[$option['exam_paper_question_id']]['options'][] = $option;
            }
        }
        return $examWithOptions;
    }
    /**
     * 试卷添加试题
     * @param $arr
     * @return void|null
     */
    public function addPage($arr = []){

        if(count($arr) < 1){
            return null;
        }
        $questionId = -1;
        $i = ExamPaperQuestion::count();
        foreach ($arr as $v){
            $examPaperQuestion = new ExamPaperQuestion();
            $examPaperQuestion->question_id = $v['id'];
            $examPaperQuestion->exam_paper_id = $v['exam_paper_id'];
            $examPaperQuestion->question_stem = $v['stem'];
            $examPaperQuestion->name = $v['name'];
            $examPaperQuestion->question_type = $v['question_type'];
            $examPaperQuestion->score = $v['score'];
            $examPaperQuestion->order = $i++;
            $examPaperQuestion->save();
            foreach ($v['options'] as $vv){
                $examQuestionOption = new ExamQuestionOption();
                $examQuestionOption->exam_paper_question_id = $examPaperQuestion->id;
                $examQuestionOption->option_content = $vv['option_content'];
                $examQuestionOption->is_correct = $vv['is_correct'];
                $examQuestionOption->order = $vv['order'];
                $examQuestionOption->save();
            }
            $questionId = $examPaperQuestion->id;;
        }
        return $questionId;
    }


    /**
     * 获取详情
     * @return
     */
    public function info($id) {
        $query = ExamPaper::where('id',$id)->first();

        return $query;
    }

    /**
     * 获取用户试卷结果
     * @return
     */
    public static function userPaperResult($users_id,$exam_paper_id,$certificate_id)
    {

        $examPaperQuestionArr = ExamPaperQuestion::where('exam_paper_id', $exam_paper_id)
            ->selectRaw('question_type, AVG(score) as average_score, SUM(score) as sum_score')->groupBy('question_type')
            ->get()->toArray();
        $userQuestionRecordArr = UserQuestionRecord::where('exam_paper_id', $exam_paper_id)->where('users_id', $users_id)
            ->where('certificate_id', $certificate_id)
            ->selectRaw('question_type, AVG(score) as average_score, SUM(score) as sum_score')->groupBy('question_type')
            ->get()->toArray();

        $element = 'sum_score';
        //试卷总分
        $paperTotalScore = array_sum(array_map(function ($user) use ($element) {
            return $user[$element];
        }, $examPaperQuestionArr));

        //用户答题总分
        $userTotalScore = array_sum(array_map(function ($user) use ($element) {
            return $user[$element];
        }, $userQuestionRecordArr));

        $UserExamRecord =UserExamRecord::where('certificate_id',$certificate_id)
            ->where('users_id',$users_id)->where('exam_paper_id',$exam_paper_id)->first();

        if($UserExamRecord && $UserExamRecord->is_submitted == 0){
            $examPaper = ExamPaper::find($exam_paper_id);
            $givenTimeLimit = $examPaper->time_limit; //考试时长
            $currentDateTime = Carbon::now(); //当前时间
            // 计算考试用了多少分钟
            $timeElapsedInMinutes = $currentDateTime->diffInMinutes($UserExamRecord->created_at);
            if($timeElapsedInMinutes > $givenTimeLimit){
                $timeElapsedInMinutes = $givenTimeLimit;
            }
            $UserExamRecord->take_time = $timeElapsedInMinutes;
            $UserExamRecord->is_submitted = 1;
            $UserExamRecord->score = $userTotalScore;
            $UserExamRecord->save();
        }

        $arr =  [
            'paperTotalScore' => $paperTotalScore,
            'userTotalScore' => $userTotalScore,
            'username' => isset($UserExamRecord->username) ? $UserExamRecord->username : '',
            'student_num' => isset($UserExamRecord->student_num) ? $UserExamRecord->student_num : '',
            'exam_paper_name' => isset($UserExamRecord->exam_paper_name) ? $UserExamRecord->exam_paper_name : '',
            'certificate_name' => isset($UserExamRecord->certificate_name) ? $UserExamRecord->certificate_name : '',
            'score' => isset($UserExamRecord->score) ? $UserExamRecord->score : '',
            'take_time' => isset($UserExamRecord->take_time) ? $UserExamRecord->take_time : '',
            'created_time' => isset($UserExamRecord->created_at) ? $UserExamRecord->created_at : '',
            'end_time' =>  isset($UserExamRecord->updated_at) ? $UserExamRecord->updated_at : '',
        ];
        return [$arr,$examPaperQuestionArr,$userQuestionRecordArr];
    }
    /**
     * 获取用户试卷列表
     * @return
     */
    public function userPaperList($username,$certificate_id,$page,$limit,$sort,$order) {
        $query = userExamRecord::query();
        if(!empty($username)){
            $query->where('user_exam_records.username','like',"%$username%");
        }
        if(!empty($certificate_id)){
            $query->where('user_exam_records.certificate_id',$certificate_id);
        }
        return $query->orderBy($sort,$order)->paginate($limit, ['*'], 'page', $page);
    }
    /**
     * 获取用户试卷详情列表
     * @return
     */
    public function userPaperInfo($users_id,$exam_paper_id,$certificate_id) {

        $UserExamRecord = UserQuestionRecord::where('exam_paper_id', $exam_paper_id) ->where('certificate_id', $certificate_id)
            ->where('users_id', $users_id)->first();
        if(isset($UserExamRecord)){
            $examPaperQuestionArr = ExamPaperQuestion::where('exam_paper_id', $exam_paper_id)
                ->selectRaw('question_type, AVG(score) as average_score, SUM(score) as sum_score')->groupBy('question_type')
                ->get()->toArray();
            $element = 'sum_score';
            //试卷总分
            $paperTotalScore = array_sum(array_map(function ($user) use ($element) {
                return $user[$element];
            }, $examPaperQuestionArr));
            $arr = [
                'paperTotalScore' => $paperTotalScore,
                'username' => isset($UserExamRecord->username) ? $UserExamRecord->username : '',
                'student_num' => isset($UserExamRecord->student_num) ? $UserExamRecord->student_num : '',
                'exam_paper_name' => isset($UserExamRecord->exam_paper_name) ? $UserExamRecord->exam_paper_name : '',
                'certificate_name' => isset($UserExamRecord->certificate_name) ? $UserExamRecord->certificate_name : '',
                'score' => isset($UserExamRecord->score) ? $UserExamRecord->score : '',
                'take_time' => isset($UserExamRecord->take_time) ? $UserExamRecord->take_time : '',
                'created_time' => isset($UserExamRecord->created_at) ? $UserExamRecord->created_at : '',
                'end_time' =>  isset($UserExamRecord->updated_at) ? $UserExamRecord->updated_at : '',
            ];
        }else{
            $arr = [];
        }



        return $arr;
    }
    /**
     * 获取用户个人中心试卷证书信息
     * @return
     */
    public static function certificationInfo($users_id)
    {
        $userExamRecord = UserExamRecord::leftJoin('certificates', 'certificates.id', '=', 'user_exam_records.certificate_id')
        ->where('users_id', $users_id)->where('is_submitted', 1)
        ->select('username','student_num','is_submitted','take_time','certificate_name','image_path','score')
        ->get()->toArray();
        return $userExamRecord;
    }
}
